package com.fdm.model.dao;

import java.sql.SQLException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.fdm.model.Customer;
import com.fdm.util.exceptions.UniqueConstraintException;

@Repository
@Transactional(propagation=Propagation.SUPPORTS)
public class HibernateCustomerDAO implements CustomerDAO {
	@Autowired
	private SessionFactory sessionFactory;
	//private Customer customer;
	
	public Customer getCustomer(long id) throws SQLException {
		Session session=sessionFactory.openSession();
		//session.beginTransaction();
		Customer customer =(Customer)session.get(Customer.class, id);
		
		return customer;
	}

	public Customer getCustomer(String email) throws SQLException{
		Session session=sessionFactory.openSession();
		Query query=session.createQuery(" FROM Customer WHERE email= ?");
		query.setString(0, email);
		Customer customer = (Customer) query.uniqueResult();
		return customer;
	}
	
	@Transactional(propagation=Propagation.SUPPORTS)
	public void createNewCustomer(Customer customer) throws UniqueConstraintException{
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try{
			session.save(customer);
			session.getTransaction().commit();
		}
		catch(ConstraintViolationException cve){
			session.getTransaction().rollback();
			throw new UniqueConstraintException("User with email address "+customer.getEmail()+" already exists");
		}
		finally{
			session.close();
		}
	}

	public void updateCustomer(Customer customer) {
		// TODO Auto-generated method stub

	}

	public void deleteCustomer(long id) {
		// TODO Auto-generated method stub

	}

}
